#!/usr/bin/env bash
#
# created by
#

# set -x # Print trace
set -u # Variables can only be used after set.
set -e # Non-zero exit status must be captured.
set -o pipefail # Return exit status of the last successful command in a pipeline.

# paths

function info() {
    datetime=`date "+%Y-%m-%d %H:%M:%S |"`
    echo -e "\033[1;94m${datetime} INFO |\033[0m\033[0;94m $@ \033[0m"
}

function error() {
    datetime=`date "+%Y-%m-%d %H:%M:%S |"`
    echo -e "\033[1;91m${datetime} ERROR |\033[0m\033[1;91m $@ \033[0m" >&2
}

readonly BUILD_ROOT_DIR="$( cd $(dirname $0) && pwd)"
readonly OUTPUT_DIR="${BUILD_ROOT_DIR}/output"
readonly OUTPUT_TEMP_DIR="${BUILD_ROOT_DIR}/output_temp"

readonly JDK_VERSION="jdk1.8.0"

function calc_cpus() {

    case "`uname`" in
        Linux)
            cpu_cores=`egrep -c 'processor([[:space:]]+):.*' /proc/cpuinfo`
        ;;
        FreeBSD)
            cpu_cores=`sysctl hw.ncpu | awk '{print $2}'`
        ;;
        SunOS)
            cpu_cores=`psrinfo | wc -l`
        ;;
        Darwin)
            cpu_cores=`sysctl hw.ncpu | awk '{print $2}'`
        ;;
        *)
            cpu_cores="2"
        ;;
    esac

    if [ "$cpu_cores" -lt "1" ] ; then
        cpu_cores="1"
    fi

    if [ "$cpu_cores" -lt "3" ] ; then
        cpu_cores="1"
    elif [ "$cpu_cores" -gt "8" ] ; then
        cpu_cores=$(($cpu_cores - 4))
    else
        cpu_cores=$(($cpu_cores - 2))
    fi

}

function prepare_jdk_env() {
    info "check jdk environment......"

    JAVA_VERSION=$(java -version 2>&1 |awk 'NR==1{ gsub(/"/,""); print $3 }')
    if [[ ${JAVA_VERSION} == 1.8.0* ]] ; then
        info "check JDK version successfully, jdk version: ${JAVA_VERSION}"
        return 0
    fi

    error "check environment failed, do not exist required ${JDK_VERSION}"
    exit 1
}

function prepare_maven_env() {

    # Check Maven Version
    info "check maven environment......"

    # 下面这条语句，在某些情况下版本号不是出现在结果的第一行，判断会出错，只能用别的方法
    # MAVEN_VERSION=$(mvn -version 2>&1 |awk 'NR==1{ gsub(/"/,""); print $3 }')
    # 在编译机上，执行当前脚本的到下面这条语句，如果grep的结果为空，会闪退；但是在编译机上单独执行下面这条语句，又能正常执行；why？
    # MAVEN_VERSION=$(mvn -version 2>&1 | grep 'Apache Maven 3.5')
    MAVEN_VERSION=$(mvn -version 2>&1)
    if [[ ${MAVEN_VERSION} == *'Apache Maven 3.5'* ]] ; then
        info "check Maven version successfully, maven version: ${MAVEN_VERSION}"
        return 0
    fi

    error "check maven environment failed"
    exit 1
}

# 配置java环境以及依赖
function env_init() {
    info "prepare environment......"

    mkdir -p ${OUTPUT_TEMP_DIR}

    prepare_jdk_env

    prepare_maven_env

}

# 编译生成可执行文件
function build() {

    info "start build ......"

    calc_cpus

    mvn clean install -Dcheckstyle.skip=true -DskipTests -T${cpu_cores}

    if [ $? -ne 0 ]; then
        error "build failed"
        exit 1
    fi
    info "build successfully"
}

function pack() {
    info "start packing......"

    rm -rf ${OUTPUT_DIR}
    mkdir -p ${OUTPUT_DIR}

    cp -rf ${BUILD_ROOT_DIR}/target/output/net-cfg-parser-*/* ${OUTPUT_DIR}/
    if [ ! -d ${OUTPUT_DIR}/lib ]; then
      mkdir -p ${OUTPUT_DIR}/lib
    fi
    cp -f ${BUILD_ROOT_DIR}/target/net-cfg-parser-*.jar ${OUTPUT_DIR}/lib/net-cfg-parser.jar

}

# 清理临时文件
function clean() {
    info "start clean......"

    rm -rf ${OUTPUT_TEMP_DIR}
}

function main() {

    env_init
    build
    pack
    clean

    info "Build done successfully"
}

main "$@"